#include <stdio.h>
#include <string.h>
#include "main.h"

int main(const int argc, const char** argv){
	struct contact data[CONTACT_MAX];
	FILE* file;
	int index = 0;
	char option, ret;
	int firstrun, cont, is_text;
	firstrun = FALSE, cont = TRUE, is_text = TRUE ; 
	if (argc != 3){
		printf("Invalid arguments...\n");
		printf("Usage: %s <file> <t - text / b- binary>\n", argv[0]);
		return (1);
	} 
	else {
		if (strcmp(argv[2], "t") == 0){
			if ((file = fopen(argv[1], "rt")) == NULL){
				firstrun = TRUE;
				printf("First time use. Creating TEXT file.\n");
			}
		} else {
			if (strcmp(argv[2], "b") == 0){
				is_text = FALSE;
				if ((file = fopen(argv[1], "rb")) == NULL){
					firstrun = TRUE;
					printf("First time use. Creating BINARY file.\n");
				} 
			} 
			else {
					printf("Invalid file type argument.\n");
					printf("Invalid arguments...\n");
					printf("Usage: %s <file> <t - text / b- binary>\n", argv[0]);
					return (1);
			}
		}
	}
	
	if (firstrun == FALSE){
		initfile(file, data, &index, is_text);
	}
	do {
		option = menu();
		scanf("%c", &ret);
		switch (option){
			case 1:
				addcontact(file, data, &index);
				break;
			case 2:
				delcontact(file, data, &index);
				break;
			case 3:
				showcontact(file, data, &index);
				break;
			case 0:
					if ((file = fopen(argv[1], "w+b")) == NULL){
						printf("Error while opening the file.\n");
						return (2);
					}	 
					recorddata(file, data, &index, is_text);
					cont = FALSE;
					break;
		}
	} while (cont == TRUE);
	fclose(file);
	return 0;		
}
